package com.guyaogg.gulimall.ware.exception;

import com.guyaogg.common.exception.BizCodeEnum;
import com.guyaogg.common.exception.MergePurchaseException;
import com.guyaogg.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理所有异常
 * @author 顾遥
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.guyaogg.gulimall.ware.controller")
public class GulimallExceptionControllerAdvice {


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){

        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errorMap = new HashMap<>(8);
        bindingResult.getFieldErrors().forEach((fieldError -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }));
        log.error("数据校验出现问题：{}，异常类型：{}", errorMap,e.getClass());
        return R.error(BizCodeEnum.VALID_EXCEPTION).put("data", errorMap);

    }
    @ExceptionHandler(value = MergePurchaseException.class)
    public R handleMergePurchaseException(MergePurchaseException e){


        log.error("采购单合并出现问题：{}，异常类型：{}", e.getMessage(),e.getClass());
        return R.error(BizCodeEnum.MERGE_PURCHASE_EXCEPTION).put("data", e.getMessage());

    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        log.error("出现异常信息：{}，异常类型：{}", throwable.getMessage(),throwable.getClass());
        throwable.printStackTrace();

        return R.error(BizCodeEnum.UNKNOW_EXCEPTION);
    }
}
